package org.bpm.view
{
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.getClassByAlias;
	import flash.system.ApplicationDomain;
	import flash.text.TextField;
	import flash.ui.Mouse;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import org.bpm.events.ProcessMapEvent;
	import org.bpm.interfaces.IMapElement;
	import org.bpm.models.MapNodeModel;
	import org.bpm.utils.AnimatedDisplayUtil;
	import org.bpm.utils.UIGenerator;
	
	/**
	 * View of a node,
	 * */
	public class MapNode extends Sprite implements IMapElement
	{
		public var model:MapNodeModel;
		private var mapElement:IMapElement;
		
		
		private var HORIZONTAL_GAP:Number = 5;
		
		public function MapNode(pModel:MapNodeModel)
		{
			super();
			model = pModel;
			x = model.rect.x + model.rect.width/2;
			y = model.rect.y + model.rect.height/2;
			
			create();
			
			mouseChildren = false;
			buttonMode = true;
			
			addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			addEventListener(MouseEvent.ROLL_OVER, overHandler);
			addEventListener(MouseEvent.ROLL_OUT, outHandler);
			addEventListener(MouseEvent.CLICK, clickHandler);
		}
		
		private function overHandler(pEvent:MouseEvent):void{
			highlight();
			dispatchEvent(new ProcessMapEvent(ProcessMapEvent.MAP_ELEMENT_OVER, model.definitionList,true));
		}
		private function outHandler(pEvent:MouseEvent):void{
			if(!model.isDone) blur();	
			dispatchEvent(new ProcessMapEvent(ProcessMapEvent.MAP_ELEMENT_OUT,model.definitionList,true));
		}
		private function clickHandler(pEvent:MouseEvent):void{
			dispatchEvent(new ProcessMapEvent(ProcessMapEvent.MAP_ELEMENT_CLICK, model.definitionList,true));
		}
		
		private function onRemovedFromStage(pEvent:Event):void{
			removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			removeEventListener(MouseEvent.ROLL_OVER, overHandler);
			removeEventListener(MouseEvent.ROLL_OUT, outHandler);
			removeEventListener(MouseEvent.CLICK , clickHandler);
			
			if(mapElement){
				removeChild((mapElement as MovieClip));
				mapElement = null;
			}
			model = null;
		}
		private function create():void{
			mapElement = (new UIGenerator()).getUI(model.type) as IMapElement;
			if(mapElement){
				addChild(mapElement as Sprite);
				//AnimatedDisplayUtil.animatedShow(mapElement as Sprite);
				mapElement.width = model.rect.width;
				mapElement.height = model.rect.height;
				updateLabel(model.label);
			}
			
			model.isDone ? highlight() : blur();
		}
		
		public function highlight():void{
			if(mapElement) mapElement.highlight();
		}
		public function blur():void{
			if(mapElement) mapElement.blur();
		}
		public function updateLabel(pValue:String):void{
			if(mapElement) mapElement.updateLabel(pValue);
		}

	}
}